define(['angularAMD'], function (angularAMD) {
    angularAMD.service('sJDSInstallerService', ['$rootScope', '$filter', '$translate', 'config', '$http', '$mdDialog', '$moduleInstaller', '$css', '$timeout',
    function($rootScope, $filter, $translate, config, $http, $mdDialog, $moduleInstaller, $css, $timeout){
        var $sJDSInstallerService = this, configDialog;
        function checkVersion(sJDSLoginInfo, callback, errorback){
            $moduleInstaller.status.msg = $filter('translate')('sJDS.msg.check_version');
            send(sJDSLoginInfo, function(data){
                if(data.url != ''){
                    //sJDSLoginInfo.version = data.version;
                    var temp_version = data.version;
                    var url = 'http://'+sJDSLoginInfo.ip+':'+sJDSLoginInfo.port+data.url;
                    if(callback)
                        callback(sJDSLoginInfo, url, temp_version);
                } else {
                    entersJDS(sJDSLoginInfo);
                }
            }, errorback);
        }

        //20190718 modify by Dustdusk for M#:
        function getsJDSInfo(callback){
            var sJDSLoginInfo = {};
            //20180420 modify by Dustdusk for M#45433:智派工的ip / port / 站台名稱 一律由SMES傳入
            sJDSLoginInfo.ip = config.server.ip;
            sJDSLoginInfo.port = config.server.port;
            sJDSLoginInfo.name = 'sJDS_'+config.setting.environment;

            sJDSLoginInfo.account = config.cache.account;
            sJDSLoginInfo.user_name = config.cache.name;
            sJDSLoginInfo.password = config.cache.password;
            sJDSLoginInfo.session = config.mdssessionno;
            sJDSLoginInfo.lang = $translate.use();
            require(['text!sJDS/config/config.json'], function(sJDSConfig){
                //找到，表示智派工已下載
                try{
                    sJDSLoginInfo.version = JSON.parse(sJDSConfig).appVersion||'0.0.0.0';
                }catch(e){
                    sJDSLoginInfo.version = '0.0.0.0';
                }
                if(typeof(callback) == 'function')
                    callback(sJDSLoginInfo);
            }, function(e){
                //找不到，表示未下載
                sJDSLoginInfo.version = '0.0.0.0';
                if(typeof(callback) == 'function')
                    callback(sJDSLoginInfo);
            });
        }

        function entersJDS(sJDSLoginInfo, version){
            if(version){
                sJDSLoginInfo.version = version;
            }
            localStorage.setItem('sJDS_login', JSON.stringify(sJDSLoginInfo));
            if(window.resolveLocalFileSystemURL){
                window.resolveLocalFileSystemURL(cordova.file.dataDirectory+'update//sJDS',
                    function(updateFolder){
                        document.location.href = updateFolder.toURL() + '//index.html';
                    },
                    function(){
                        $sJDSInstallerService.showConfigDialog();
                    }
                );
            } else {
                document.location.href = 'sJDS/index.html';
            }
        }

        function combineIP(array){
            var totalip;
            array.forEach(function(ipstring){
                if(!totalip)
                    totalip = ipstring;
                else
                    totalip += '.' +ipstring;
            });
            return totalip;
        }

        function doUpdate(sJDSLoginInfo, dialog){
            $sJDSInstallerService.update(sJDSLoginInfo, function(sJDSLoginInfo, version){
                $timeout(function(){
                    entersJDS(sJDSLoginInfo, version);
                });
            }, function(msg){
                $timeout(function(){
                    dialog.mode = 'setting';
                });
            });
        }

        function send(sendData, callback, errorback){
            var lang = {
                'zh_CN':'Chs',
                'zh_TW':'Chs',
                'en_US':'Eng'
            };
            var data = {
                url: 'http://' + sendData.ip + ':' + sendData.port + '/'+sendData.name+'/Api/Adapter',
                method : 'POST',
                headers : {
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                data :{
                    uri:'IUpdateService',
                    method:'GetUpdate',
                    userNo:sendData.account,
                    applicationId:config.applicationId,
                    cookie:'',
                    session:sendData.session,
                    language:lang[sendData.lang],
                    data:sendData.version
                }
            };
            $http(data).success(function(data, status, headers) {
                $rootScope.hideLoading();
                if(data.success){
                    callback(data.result);
                } else {
                    //$rootScope.showAlert(data.message, errorback);
                    $moduleInstaller.status.msg = data.message;
                    if(errorback)
                        errorback();
                }
            }).error(function(respose,status_code,c,d){
                $rootScope.hideLoading();
                $moduleInstaller.status.msg = status_code;
                if(errorback)
                    errorback();
                //$rootScope.showAlert(respose, errorback);
            });
        }

        $sJDSInstallerService.update = function(sJDSLoginInfo, callback, errorback){
            checkVersion(sJDSLoginInfo,
                function(sJDSLoginInfo, url, version){
                    $moduleInstaller.update({
                        url:url,
                        root_path:'sJDS',
                        callback:function(){
                            if(callback){
                                callback(sJDSLoginInfo, version);
                            }
                        },
                        errorback:function(){
                            if(errorback){
                                errorback();
                            }
                        }
                    });
                }, function(){
                    if(errorback){
                        errorback();
                    }
                }
            );
        }

        $sJDSInstallerService.back = function(){
            localStorage.setItem('SMES_login', localStorage.getItem('sJDS_login'));
            if(window.resolveLocalFileSystemURL){
                window.resolveLocalFileSystemURL(cordova.file.dataDirectory+'update', function(updateFolder){
                    document.location.href = updateFolder.toURL() + '/index.html';
                }, function(){
                    document.location.href = '../index.html';
                });
            } else {
                document.location.href = '../index.html';
            }
        };

        $sJDSInstallerService.open = function(content){
            if(content.mode == 'setting'){
                $moduleInstaller.status.msg = $filter('translate')('sJDS.msg.input_server_info');
            }
            if(content.msg){
                $moduleInstaller.status.msg = content.msg;
            }
            getsJDSInfo(function(sJDSLoginInfo){
                $mdDialog.dialog(
                    'JSplugins/ModuleInstaller/sJDSConfig.tmp.html',
                    function(dialog){
                        configDialog = dialog;
                        return {
                            mode:content.mode,
                            serverIp: sJDSLoginInfo.ip.split('.'),
                            port: sJDSLoginInfo.port,
                            server_name: sJDSLoginInfo.name,
                            status:$moduleInstaller.status,
                            beforeShown: function(){
                                $css.add('JSplugins/ModuleInstaller/sJDSConfig.css');
                                componentHandler.upgradeAllRegistered();
                                if(content.mode != 'setting'){
                                    $timeout(function(){
                                        doUpdate(sJDSLoginInfo, dialog);
                                    }, 200);
                                }
                            },
                            confirm:function(){
                                dialog.mode = undefined;
                                sJDSLoginInfo.ip = combineIP(dialog.serverIp);
                                sJDSLoginInfo.port = dialog.port;
                                sJDSLoginInfo.name = dialog.server_name;
                                //localStorage.setItem('sJDS_login', JSON.stringify(sJDSLoginInfo));
                                $timeout(function(){
                                    doUpdate(sJDSLoginInfo, dialog);
                                }, 200);
                            },
                            cancel:function(){
                                $css.remove('JSplugins/ModuleInstaller/sJDSConfig.css');
                                dialog.hide();
                            }
                        };
                    }
                );
            });
        };
    }]);
});
